package com.henghai.zhenxuan;


import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.appcompat.app.AppCompatActivity;

import com.henghai.zhenxuan.data.api.LoginApi;
import com.henghai.zhenxuan.data.config.AppConfig;
import com.henghai.zhenxuan.data.config.Const;
import com.henghai.zhenxuan.data.repository.DataRepository;
import com.henghai.zhenxuan.ui.page.login.LoginActivity;
import com.henghai.zhenxuan.utils.MainHandler;
import com.henghai.zhenxuan.utils.Utils;
import com.blankj.utilcode.util.BarUtils;
import com.kongzue.dialogx.dialogs.MessageDialog;
import com.windmill.sdk.WindMillError;
import com.windmill.sdk.models.AdInfo;
import com.windmill.sdk.splash.IWMSplashEyeAd;
import com.windmill.sdk.splash.WMSplashAd;
import com.windmill.sdk.splash.WMSplashAdListener;
import com.windmill.sdk.splash.WMSplashAdRequest;
import com.windmill.sdk.splash.WMSplashEyeAdListener;

import java.util.HashMap;
import java.util.Map;

public class SplashActivity extends AppCompatActivity {
    private int requestCode;
    private boolean canJump = false;
    private WMSplashAd mSplashAd;
    private FrameLayout splash_ad_container;
    private static final String TAG = "MainActivity-开屏";

    public static void launch(Context context) {
        launch(context, 0);
    }

    public static void launch(Context context, int requestCode) {
        Intent intent = new Intent(context, SplashActivity.class);
        intent.putExtra("request_code", requestCode);
        context.startActivity(intent);
    }

    private void initPrivacyTipLink() {
        if (AppConfig.INSTANCE.getMConfigs().agree().get() == null || !AppConfig.INSTANCE.getMConfigs().agree().get()) {
            MessageDialog.show("隐私政策协议", Utils.getPrivacyContent(getString(R.string.privacy_content))).setCancelButton("暂不同意", (messageDialog, view) -> {
                AppConfig.INSTANCE.getMConfigs().agree().set(false);
                finish();
                return false;
            }).setOkButton("同意", (messageDialog, view) -> {
                AppConfig.INSTANCE.getMConfigs().agree().set(true);
                init();
                return false;
            }).setCancelable(false);
        } else {
            init();
        }
    }


    private void init() {
        if (AppConfig.INSTANCE.getMConfigs().token().get() != null && AppConfig.INSTANCE.getMConfigs().userName().get() != null && AppConfig.INSTANCE.getMConfigs().userPwd().get() != null &&
                !AppConfig.INSTANCE.getMConfigs().token().get().isEmpty() && !AppConfig.INSTANCE.getMConfigs().userName().get().isEmpty() && !AppConfig.INSTANCE.getMConfigs().userPwd().get().isEmpty()) {
            String packageName = getPackageName();
            String phoneSha1 = Utils.getSha1(this);
            DataRepository.getInstance().login(SplashActivity.this, new LoginApi(AppConfig.INSTANCE.getMConfigs().userName().get(),
                    AppConfig.INSTANCE.getMConfigs().userPwd().get(), packageName, phoneSha1), dataResult -> {
                if (!dataResult.getResponseStatus().isSuccess()) {
                    LoginActivity.launch(SplashActivity.this);
                    this.finish();
                    return;
                }
                AppConfig.INSTANCE.getMConfigs().token().set(dataResult.getResult().getData().getToken());
                AppConfig.INSTANCE.getMConfigs().login().set(dataResult.getResult().getData());
//                String SplashKey = AppConfig.INSTANCE.getMConfigs().login().get().getPlacementIdOne();
                String SplashKey = AppConfig.INSTANCE.getMConfigs().login().get().getTobidSplash();
//                SplashKey = "1432972458851579";
                Log.d(TAG, "init: "+ SplashKey);
                if (Const.ISSHOWAD) {//是否显示开屏广告
                    //初始化开屏广告
                    if (SplashKey != null && !SplashKey.isEmpty()) {
                        initSplashAd(SplashKey);//初始化开屏广告
                    } else {
                        jumpToMain();
                    }
                } else {
                    jumpToMain();
                }

            });
        } else {
            LoginActivity.launch(SplashActivity.this);
            this.finish();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT);
        BarUtils.setStatusBarLightMode(this, true);
        super.onCreate(savedInstanceState);
        requestCode = getIntent().getIntExtra("request_code", 0);
        setContentView(R.layout.activity_splash);
        initPrivacyTipLink();
        splash_ad_container = findViewById(R.id.splash_ad_container);
    }

//    private ATShowConfig getATShowConfig() {
//        ATShowConfig.Builder builder = new ATShowConfig.Builder();
//        builder.scenarioId(Const.SCENARIO_ID.SPLASH_AD_SCENARIO);
//        builder.showCustomExt(Const.SHOW_CUSTOM_EXT.SPLASH_AD_SHOW_CUSTOM_EXT);
//
//        return builder.build();
//    }


    private void initSplashAd(String placementId) {
        int requestSplashWidth = 0;
        int requestSplashHeight = 0;

        Configuration cf = getResources().getConfiguration();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int ori = cf.orientation;
        if (ori == Configuration.ORIENTATION_LANDSCAPE) {
            requestSplashWidth = (int) (dm.widthPixels * 0.85);
            requestSplashHeight = dm.heightPixels;
        } else {
            requestSplashWidth = dm.widthPixels;
            requestSplashHeight = (int) (dm.heightPixels * 0.85);
        }
        String userId = AppConfig.INSTANCE.getMConfigs().user().get().getUserId() + "";
        if (userId == null || userId.isEmpty()) {
            userId = "0";
        }
        WMSplashAdRequest adRequest = new WMSplashAdRequest(placementId, userId, null);
        mSplashAd = new WMSplashAd(this, adRequest, new WMSplashAdListener() {
            @Override
            public void onSplashAdSuccessPresent(AdInfo adInfo) {
                Log.d(TAG, "onSplashAdSuccessPresent: " + adInfo.toString());
            }

            @Override
            public void onSplashAdFailToPresent(WindMillError error, String placementId) {
                Log.d(TAG, "onSplashAdFailToPresent: " + placementId + " error:" + error.toString());
                MainHandler.INSTANCE.postDelay(400, SplashActivity.this::jumpToMain);
            }

            @Override
            public void onSplashAdSuccessLoad(String s) {
                Log.d(TAG, "onSplashAdSuccessLoad: " + placementId);
                boolean isReady = mSplashAd.isReady();
//                ATAdStatusInfo atAdStatusInfo = mSplashAd.checkAdStatus();
                if (isReady) {
                    mSplashAd.showAd(splash_ad_container);
//                    mSplashAd.show(SplashActivity.this, splash_ad_container, null, getATShowConfig()); //展示开屏广告
                } else {
                    initSplashAd(placementId);
                }
            }

            @Override
            public void onSplashAdFailToLoad(WindMillError windMillError, String s) {
                Log.d(TAG, "onSplashAdFailToLoad: " + placementId + " error:" + windMillError.toString());
                MainHandler.INSTANCE.postDelay(400, SplashActivity.this::jumpToMain);
            }
            @Override
            public void onSplashAdClicked(AdInfo adInfo) {
                Log.d(TAG, "onSplashAdClicked: " + adInfo.toString());
            }

            @Override
            public void onSplashClosed(AdInfo adInfo, IWMSplashEyeAd iwmSplashEyeAd) {
                Log.d(TAG, "onSplashClosed: " + adInfo.toString());
                MainHandler.INSTANCE.postDelay(400, SplashActivity.this::jumpToMain);
                //展示点睛广告
//                showSplashEyeAd(splashEyeAd);
            }
        });
        mSplashAd.loadAdOnly();
//        mSplashAd = new ATSplashAd(this, placementId, new SplashListener() {
//            @Override
//            public void onAdLoaded(boolean b) {
//                super.onAdLoaded(b);
//                ATAdStatusInfo atAdStatusInfo = mSplashAd.checkAdStatus();
//                if (atAdStatusInfo.isReady()) {
//                    mSplashAd.show(SplashActivity.this, splash_ad_container, null, getATShowConfig()); //展示开屏广告
//                } else {
//                    initSplashAd(placementId);
//                }
//            }
//
//            @Override
//            public void onNoAdError(AdError adError) {
//                super.onNoAdError(adError);
//                MainHandler.INSTANCE.postDelay(1000, SplashActivity.this::jumpToMain);
//            }
//
//            @Override
//            public void onAdDismiss(ATAdInfo atAdInfo, ATSplashAdExtraInfo atSplashAdExtraInfo) {
//                super.onAdDismiss(atAdInfo, atSplashAdExtraInfo);
//                MainHandler.INSTANCE.postDelay(1000, SplashActivity.this::jumpToMain);
//            }
//
//            @Override
//            public void onAdLoadTimeout() {
//                super.onAdLoadTimeout();
//                MainHandler.INSTANCE.postDelay(1000, SplashActivity.this::jumpToMain);
//            }
//
//            @Override
//            public void onAdClick(ATAdInfo atAdInfo) {
//                super.onAdClick(atAdInfo);
//                Log.d(TAG, "onAdClick: " + atAdInfo.toString());
//            }
//
//            @Override
//            public void onAdShow(ATAdInfo atAdInfo) {
//                super.onAdShow(atAdInfo);
//                Log.d(TAG, "onAdShow: " + atAdInfo.toString());
//            }
//        }, 5000);
//        Map<String, Object> localMap = new HashMap<>();
//        //穿山甲开屏广告支持传入宽高，单位px
//        localMap.put(ATAdConst.KEY.AD_WIDTH, requestSplashWidth);
//        localMap.put(ATAdConst.KEY.AD_HEIGHT, requestSplashHeight);
//        mSplashAd.setLocalExtra(localMap);
//        mSplashAd.loadAd();

    }

    private void jumpToMain() {
        if (canJump) {
            if (AppConfig.INSTANCE.getMConfigs().agree().get() == null || !AppConfig.INSTANCE.getMConfigs().agree().get()) {
                return;
            }
            doJump();
        } else {
            canJump = true;
        }
    }

    private void doJump() {
        if (requestCode == 0) { //冷启动进入开屏页，接下来要跳到首页；否则只需要关闭当前页面即可
            if (AppConfig.INSTANCE.getMConfigs().user() == null
                    || AppConfig.INSTANCE.getMConfigs().user().get() == null
                    || AppConfig.INSTANCE.getMConfigs().token().get() == null
                    || AppConfig.INSTANCE.getMConfigs().token().get().isEmpty()) {
                LoginActivity.launch(this);
                this.finish();
            } else {
                MainActivity.launch(this);
                this.finish();
            }
        }

    }

    protected void onDestroy() {
        super.onDestroy();
        if (splash_ad_container != null) {
            splash_ad_container.removeAllViews();
        }
        if (mSplashAd != null) {
//            mSplashAd.setAdListener(null);
//            mSplashAd.setAdDownloadListener(null);
//            mSplashAd.setAdSourceStatusListener(null);
//            mSplashAd.destroy();
        }
//        countDownTimer.cancel();
    }

    @Override
    protected void onPause() {
        super.onPause();
        canJump = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (canJump) {
//            doJump();
//        }
        canJump = true;
    }

    //防止用户返回键退出APP
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
